package monitor

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"math"
	"ruoyi-go/app/admin/model/constants"
	"ruoyi-go/app/admin/model/monitor"
	"ruoyi-go/pkg/cache/redisCache"
	"ruoyi-go/utils/R"
	"strings"
)

func ListOnLine(context *gin.Context) {
	//TODO 搜索条件
	var ipaddr = context.DefaultQuery("ipaddr", "")
	println(ipaddr)
	var userName = context.DefaultQuery("userName", "")
	println(userName)

	key := constants.LoginCacheKey + "*"
	keyList, _, _ := redisCache.RedisDB.Scan(0, key, math.MaxInt)
	rows := []monitor.LoginUserCache{}
	for i := range keyList {
		keyString := keyList[i]
		result, _ := redisCache.RedisDB.Get(keyString)
		var loginUser monitor.LoginUserCache
		json.Unmarshal([]byte(result), &loginUser)
		rows = append(rows, loginUser)
	}

	search := []monitor.LoginUserCache{}

	for i := range rows {
		row := &rows[i]

		if userName != "" || row.UserName == userName {
			if strings.Contains(userName, row.UserName) {
				search = append(search, *row)
			}
		}

		if ipaddr != "" || row.Ipaddr == ipaddr {
			if strings.Contains(ipaddr, row.Ipaddr) {
				search = append(search, *row)
			}
		}
	}

	if userName != "" || ipaddr != "" {
		res := make(map[string]any)
		res["total"] = len(search)
		res["rows"] = search
		R.SuccessData(context, res)
		return
	}

	res := make(map[string]any)
	res["total"] = len(rows)
	res["rows"] = rows
	R.SuccessData(context, res)
}

func DetectOnLine(context *gin.Context) {
	var tokenId = context.Param("tokenId")
	var key = constants.LoginCacheKey + tokenId
	_, error := redisCache.RedisDB.Del(key)
	if error != nil {
		panic(error.Error())
	}
	R.Success(context)
}
